/**
 * Created with IntelliJ IDEA.
 * User: admin
 * Date: 15-2-11
 * Time: 下午2:01
 * To change this template use File | Settings | File Templates.
 */
var meter;
var timeTrue = true;
var stepIndex;
var testPlan = {
    initPage: function () {
        $('#myModal').modal("hide");
        $("#lastTimeFileSize").val(0);
        $("#btnSave").remove();
        $("#step2").hide();
        $("#step1").show();
        $("#btnNext").show();
        $("#btnSave").hide();
        $("#btnPrev").attr("disabled", "disabled");
        stepIndex = 1;
    },
    savePlan: function () {
        var url = "/testPlanController/addTestPlan";
        var testPlanId = $("#testPlanId").val();
        var testPlanName = $("#testPlanName").val();
        var runMode = $.trim($("#runMode").val());
        var sendTo = $.trim($("#sendTo").val());
        var weekTimeList = testPlan.checkBoxValue("weekTime");
        var hhTime = $("#hh").val();
        var mmTime = $("#mm").val();
        var testCaseIds = [];
        $("input[name='testcaseId']").each(
            function () {
                testCaseIds.push($(this).val());
            }
        );
        $.ajax({
            url: url,
            type: "post",
            dataType: "json",
            traditional: true,
            async: true,
            data: {
                testPlanId: testPlanId,
                testPlanName: testPlanName,
                runMode: runMode,
                sendTo: sendTo,
                projectId: projectId,
                weekTimeList: JSON.stringify(weekTimeList),
                hhTime: hhTime,
                mmTime: mmTime,
                testCaseIds: testCaseIds
            }, success: function (result) {
                if (result.success) {
                    toastr.success("保存成功");
                    // testPlan.getTestPlan();
                    //跳转页面
                    //刷新左侧树,并且选中树
                    window.location.href = "/testPlanController/planPage";
                } else {
                    toastr.error(result.msg);
                }
            }
        });
    }
    ,
    /**
     * 打开创建测试计划页面
     * **/
    buildTestPlan() {
        /**清除运行页面的内容**/
        $("#runBuildTest").hide();
        /**清除没有计划提示**/
        $("#noPlanAlert").hide();
        /**清除计划内容**/
        $("#topTitle").hide();
        /**初始化下一步等按钮**/
        testPlan.initPage();
        /**清除计划的内容**/
        $("#testPlanId").val(null);
        $("#testPlanName").val(null);
        $("#runMode").val(1);
        $("#sendTo").val(null);
        $("#weekTime").click(function () {
            $("input:checkbox").removeAttr("checked");
        });
        $("#hh").val("0");
        $("#mm").val("0");
        /**
         * 清除用例内容
         * **/
        $("#rightCaseNumber").val(0);
        var treeObj = $.fn.zTree.getZTreeObj("rightTree");
        if (null != treeObj) {
            var nodes = treeObj.getNodes();
            for (var i = 0, l = nodes.length; i < l; i++) {
                treeObj.removeNode(nodes[i]);
            }
        }
        $("#rightCaseTable").empty();

        $("#buildTestPlan").show();
    },
    /**
     * 取消编辑测试计划
     * **/
    cancelBuildTestPlan() {
        $("#topTitle").show();
        $("#buildTestPlan").hide();
    }
    ,
    checkBoxValue: function (checkName) {
        var weekTimeList = [];
        $("input[name='" + checkName + "']").each(function () {
            if (this.checked == true) {
                weekTimeList.push(this.value);
            }
        });
        return weekTimeList;
    },
    /**
     * 编辑测试计划
     * **/
    editPlan: function () {
        testPlan.initPage();
        $("#active1").addClass("active");
        $("#btnSave").remove();
        $("#step1").show();
        $("#btnNext").show();
        $("#buildTestPlan").show();
        var testPlanId = $("#testPlanId").val();
        var requestUrl = "/testPlanController/getTestPlanById";
        $.post(requestUrl,
            {
                testPlanId: testPlanId
            },
            function (result, status) {
                if (result.success) {
                    var testPlanObj = result.obj;
                    $("#testPlanName").val(testPlanObj.testPlanName);
                    $("#sendTo").val(testPlanObj.sendTo);
                    $("#runMode").val(testPlanObj.runMode);
                    if (null != testPlanObj.hhTime) {
                        $("#hh").val(testPlanObj.hhTime);
                    }
                    if (null != testPlanObj.mmTime) {
                        $("#mm").val(testPlanObj.mmTime);
                    }
                    $("input[name='weekTime']").removeAttr("checked");
                    if (null != testPlanObj.weekTimeList) {
                        var weekList = $.parseJSON(testPlanObj.weekTimeList);
                        weekList.forEach(function (value) {
                            $("input[name='weekTime'][value=" + value + "]").attr("checked", true);
                        });
                    }
                    $("#topTitle").hide();
                    $("#buildTestPlan").show();
                    var testPlanDetailList = testPlanObj.testPlanDetailList;
                    planTree.editTestPlanMoveCase(testPlanDetailList);
                }
            }, "json");
    }
    ,
    /**
     * 删除测试计划
     * **/
    deletePlan: function () {
        var testPlanId = $("#testPlanId").val();
        var testPlanName = $("#topTestPlanName").text();
        Ewin.confirm({message: "确认要删除测试计划【" + testPlanName + "】吗？"}).on(function (e) {
            if (!e) {
                return;
            }
            $.ajax({
                type: "post",
                url: "/testPlanController/deleteInterfaceMock",
                data: {testPlanId: testPlanId},
                success: function (result) {
                    if (result.success) {
                        toastr.success('删除数据成功');
                        $("#dataTable").bootstrapTable('refresh');
                    } else {
                        toastr.error(result.msg);
                    }
                },
                error: function () {
                    toastr.error('Error');
                },
                complete: function () {

                }

            });
        });
    }
    ,
    btnNext: function () {
        if (stepIndex < 2) {
            $("#active" + stepIndex).removeClass("active");
            $("#step" + stepIndex).hide();
            stepIndex += 1;
            $("#active" + stepIndex).addClass("active");
            $("#step" + stepIndex).show();
        }
        if (stepIndex > 1) {
            $('#btnPrev').removeAttr("disabled");
        }
        if (stepIndex == 2) {
            // planTree.initTree();
            // testPlan.initTestCase();

            $("#btnNext").hide();
            $("#btnDiv").append('<button class="btn btn-success btn-next" style="width: 90px" data-last="Finish" id="btnSave" onclick="testPlan.btnSubmit()">保 存 <i class="fa fa-floppy-o"></i></button>');
        } else {
            $("#btnSave").remove();
        }
    }
    ,
    btnPrev: function () {
        if (stepIndex > 1) {
            $("#active" + stepIndex).removeClass("active");
            $("#step" + stepIndex).hide();
            stepIndex -= 1;
            $("#step" + stepIndex).show();
            $("#active" + stepIndex).addClass("active");
        }
        if (stepIndex == 1) {
            $("#btnPrev").attr("disabled", "disabled");
        }
        if (stepIndex < 2) {
            $("#btnSave").remove();
            $("#btnNext").show();
        }
    }
    ,
    btnSubmit: function () {
        testPlan.savePlan();
    }
    , initTestCase: function () {
        var url = "/testCaseController/findTestCaseGroupInterface";
        $.ajax({
            url: url,
            type: "post",
            dataType: "json",
            data: {
                projectId: projectId
            }, success: function (result) {
                if (result.success) {
                    var zNodes = result.obj;
                    var treeObj = $.fn.zTree.getZTreeObj("leftTree");
                    treeObj.addNodes(null, zNodes);
                } else {

                }
            }
        })
    },
    /**刷新主页面的执行结果**/
    getBuildPlan: function (buildTestId) {
        var url = "/testPlanController/getBuildTest";
        $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            data: {
                buildTestId: buildTestId
            }, success: function (result) {
                if (result.success) {
                    var buildTest = result.obj;
                    try {
                        var status = buildTest.status;
                        if (status != 4) {
                            timeTrue = false;
                            clearTimeout(meter);
                        }
                    } catch (e) {
                        timeTrue = false;
                        clearTimeout(meter);
                    }
                    testPlan.writeBuildTest(buildTest);
                } else {

                }
            }, error: function () {
                timeTrue = false;
                clearTimeout(meter);
            }
        })
    },
    /**
     * 写入运行中构建信息
     * **/
    writeBuildTest: function (buildTest) {
        $("#runBuildDiv").empty();
        var startTitle = "<h3>执行报告</h3>\n" +
            "    </br></br>\n" +
            "    <table class='table table-striped table-bordered'>\n" +
            "        <thead>\n" +
            "        <tr>\n" +
            "            <th style='text-align: center;'>构建id</th>\n" +
            "            <th style='text-align: center;'>计划名称</th>\n" +
            "            <th style=\"text-align: center\">运行状态</th>\n" +
            "            <th style='text-align: center;'>用例总数</th>\n" +
            "            <th style='text-align: center;'>通过数</th>\n" +
            "            <th style='text-align: center;'>通过率</th>\n" +
            "            <th style=\"text-align: center\">开始时间</th>\n" +
            "            <th style='text-align: center;'>运行时长(分)</th>\n" +
            "            <th style=\"text-align: center\">日志</th>\n" +
            "            <th style=\"text-align: center\">运行人</th>\n" +
            "        </tr>\n" +
            "        </thead>\n" +
            "        <tbody id='planView_taskList'>\n" +
            "        <tr style=\"text-align: center\"><td style='width: 7%;'>" + buildTest.buildTestId + "</td>\n" +
            "            <td style='width: 15%;'>" + buildTest.testPlanName + "</td>\n" +
            "            <td style=\"width: 7%\">" + testPlan.statusSwitch(buildTest.status) + " </td>\n" +
            "            <td style='width: 7%;'>" + buildTest.caseSize + "</td>\n" +
            "            <td style='width: 5%;'>" + buildTest.passCaseSize + "</td>\n" +
            "            <td style='width: 5%;'>" + buildTest.passRate + "</td>\n" +
            "            <td style=\"width: 10%\">" + buildTest.startTime + "</td>\n" +
            "            <td style='width: 7%;'>" + buildTest.runTime + "</td>\n" +
            "            <Td style=\"width: 5%\"><a  onclick='$(\"#myModal\").modal(\"show\")'>查看日志</a></Td>\n" +
            "            <td style=\"width: 7%\">" + buildTest.userName + "</td>\n" +
            "        </tr>\n" +
            "        </tbody>\n" +
            "    </table>\n"

        var startDetail = "<div id=\"buildTestDetail\" style=\"margin-top: 5%\">" +
            "     <h3>执行详情</h3>" +
            "     </br></br>" +
            "     <table class='table table-striped table-bordered'>" +
            "         <tr>" +
            "             <th>运行接口</th>\n" +
            "             <th>运行状态</th>\n" +
            "             <th>用例数量</th>\n" +
            "             <th>通过数量</th>\n" +
            "             <th>通过率</th>\n" +
            "             <th>运行时间</th>\n" +
            "             <th>操作</th>\n" +
            "         </tr>";
        var list = buildTest.buildTestInterfaceList;
        var tr="";
        list.forEach(function (buildTestInterface) {
            tr += "<tr>" +
                "                 <td>" + buildTestInterface.interfaceAliasName + "</td>\n" +
                "                 <td>" + testPlan.statusSwitch(buildTestInterface.status) + "</td>\n" +
                "                 <td>" + buildTestInterface.caseSize + "</td>\n" +
                "                 <td>" + buildTestInterface.passCaseSize + "</td>\n" +
                "                 <td>" + buildTestInterface.passRate + "</td>\n" +
                "                 <td>" + buildTestInterface.runTime + "</td>\n" +
                "                 <td>\n" +
                "                     <a href=\"/testPlanController/buildTestCasePage?buildTestId=" + buildTest.buildTestId + "" +
                "&interfaceId=" + buildTestInterface.interfaceId + "\">查看用例</a>\n" +
                "                 </td>\n" +
                "             </tr>";
        });
        var end = "</table></div></div>";
        $("#runBuildDiv").append("<div id=\"runBuildTest\">" + startTitle + startDetail + tr + end);
    },
    /**
     * 构建定时器，3秒刷新一次
     * **/
    buildTestRefresh: function () {
        testPlan.getBuildPlan($("#buildTestId").val());
        testPlan.getReportLog();
        testPlan.getBuildTestByProjectId();
        if (timeTrue) {
            //指定5秒刷新一次
            meter = setTimeout("testPlan.buildTestRefresh()", 3000);
        }
    },
    /**
     * 获取运行状态
     * **/
    statusSwitch: function (status) {
        var msg;
        switch (status) {
            case -1:
                msg = "<img src='/images/status/red.gif'>接口下无用例";
                break;
            case 1:
                msg = "<img src='/images/status/green.gif'>全部通过";
                break;
            case 2:
                msg = "<img src='/images/status/red.gif'>全部失败";
                break;
            case 3:
                msg = "<img src='/images/status/yellow.gif'>部分通过";
                break;
            default:
                msg = "<img src='/images/status/blue_anime.gif'>运行中";
                break;

        }
        return msg;
    },
    /**
     * 获取执行日志
     * **/
    getReportLog: function () {
        /**获取执行日志**/
        var url = "/testPlanController/runLog";
        var lastTimeFileSize = $("#lastTimeFileSize").val();
        var buildTestId = $("#buildTestId").val();
        $.ajax({
            url: url,
            type: "get",
            data: {
                buildTestId: buildTestId,
                lastTimeFileSize: lastTimeFileSize
            }, success: function (result) {
                if (null != result) {
                    $("#reportLog").append(result.strReport);
                    $("#lastTimeFileSize").val(result.lastTimeFileSize);
                }
            }, error: function (result) {
                console.info(result)
            }
        })
    },
    /**
     * 跳转运行历史
     * **/
    goHistory: function (buildTestId) {
        window.location.href = "/testPlanController/planPage?buildTestId=" + buildTestId;

    },
    /**
     * 项目id获取构建信息
     * **/
    getBuildTestByProjectId: function () {
        /**右侧的执行历史列表**/
        var url = "/testPlanController/getBuildTestByProjectId";
        $.ajax({
            url: url,
            dataType: "json",
            type: "post",
            data: {
                projectId: projectId
            }, success: function (result) {
                if (null != result) {
                    $("#historyTable").empty();
                    result.forEach(function (buildTest) {
                        var tr = "<tr><td>";
                        switch (buildTest.status) {
                            case 1:
                                tr += "<img src=\"/images/status/green.gif\">";
                                break;
                            case 2:
                                tr += "<img src=\"/images/status/red.gif\">";
                                break;
                            case 3:
                                tr += "<img src=\"/images/status/yellow.gif\">";
                                break;
                            default:
                                tr += "<img src=\"/images/status/blue_anime.gif\">";
                        }
                        tr += "<td><a  onclick='testPlan.goHistory(" + buildTest.buildTestId + ")'>" + buildTest.startTime + "</a></td></tr>";
                        $("#historyTable").append(tr);
                    })
                }
            }
        })
    }
    ,
    /**
     * 画测试计划趋势图
     * **/
    buildTrend: function (data) {
        var thred = "<div class=\"row\">\n" +
            "              <section class=\"col-lg-12 connectedSortable\">\n" +
            "                  <!-- Custom tabs (Charts with tabs)-->\n" +
            "                  <div class=\"nav-tabs-custom\">\n" +
            "                      <!-- Tabs within a box -->\n" +
            "                      <ul class=\"nav nav-tabs pull-right\">\n" +
            "                          <li class=\"active\"><a href=\"#revenue-chart\" data-toggle=\"tab\">Area</a></li>\n" +
            "                          <li class=\"pull-left header\"><i class=\"fa fa-inbox\"></i>构建用例通过率趋势表</li>\n" +
            "                      </ul>\n" +
            "                      <div class=\"tab-content no-padding\">\n" +
            "                          <!-- Morris chart - Sales -->\n" +
            "                          <div class=\"chart tab-pane active\" id=\"revenue-chart\"\n" +
            "                               style=\"position: relative; height: 300px;\"></div>\n" +
            "                          <div class=\"chart tab-pane\" id=\"sales-chart\" style=\"position: relative; height: 300px;\"></div>\n" +
            "                      </div>\n" +
            "                  </div>\n" +
            "              </section>\n" +
            "         </div>";

        $("#buildTrend").empty();
        $("#buildTrend").append(thred);
        var area = new Morris.Area({
            element: 'revenue-chart',
            data: data,
            xkey: 'startTime',
            ykeys: ['caseSize', 'passRate'],
            labels: ['执行用例数量', '通过率'],
            lineColors: ['#a0d0e0', '#3c8dbc'],
            hideHover: 'auto'
        });
    }
};
